using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using ARR.Entities.ComponentModel;
using System.Runtime.Serialization;

namespace ARR.Entities.Common
{

    [DataContract]
    [Serializable]
    public class RegexValidation : ValidationBase
    {

        private string _regex;

        public RegexValidation(string propertyName, string errorMessage, string regex, string displayName = null) : base(propertyName, errorMessage)
        {
            string fieldName = displayName == null ? propertyName : displayName;
            _regex = regex;
        }


        public override bool Validate(ValidatableEntity entity)
        {
            PropertyInfo pi = entity.GetType().GetProperty(this.PropertyName);
            if (pi == null)
                throw new Exception(string.Format("The Property '{0}' is not a valid property name", this.PropertyName));
            Match m = Regex.Match(pi.GetValue(entity, null).ToString(), _regex);
            if (m.Success)
            {
                return true;
            }
            else return false;
        }
    }
}
